$(document).ready(
//inital textarea
function() {
	$('#input').dblclick(textarea_click);
	$('#input').mouseup(textarea_click);
	
});

function synonymous_click(event){
	if($(this).attr('checked') == true){
		$('#input').replaceSelectedText($(this).val());
	}
	else{
		
	}
}



function textarea_click() {
	//alert("click double");
	$('#input').focus();
	var selectionObj = $('#input').getSelection();

	var selection = selectionObj.text.Trim();

	if (selection == '') {		
		return false;
	}	
	//get selection pass to services
	//http://localhost:8080/articlewritebee/
	var baseUrl = '/index.php/spin/query';

	$('#searchWord').val(selection);
	
	var request = $.ajax({
		type : 'POST',
		url : baseUrl,
		data : {
			word : selection
		},
		dataType : 'html'
	});
	
	$('#middleProgress').show();
	request.fail(function(jqXHR, textStatus) {
		$('#middleProgress').hide();
		alert("Request failed: please wait for a while and retry");
	});
	request.done(function(msg) {
		$("#synonymousPanelList").html(msg);
		$('#middleProgress').hide();
		$('.check-with-label').bind("click",function(){
			$('#input').focus();
			var curr = $(this)[0];
			var selectArea = $('#input').getSelection();
			var selection = selectArea.text.Trim();
			var selectStart = selectArea.start;
			var selectEnd = selectArea.start + selection.length;
			$('#input').setSelection(selectStart,selectEnd); //remove blank
			var synonymous = curr.value;
			var isReplaced = selection.indexOf('{') > -1 && selection.indexOf('}') > -1 && selection.indexOf('{') > -1 
			var isContain = selection.indexOf(synonymous) > -1;
			if(curr.checked == true){				
				if(isReplaced){
					if(!isContain){
						synonymous = '|' + synonymous;
						$('#input').insertText(synonymous,selectEnd - 1, false);
						$('#input').setSelection(selectStart,selectEnd + synonymous.length);
					}					
				}
				else{
					var replaced = '{' + selection + '|' + synonymous + '}';
					$('#input').replaceSelectedText(replaced);
					$('#input').setSelection(selectStart, selectStart + replaced.length);
				}
			}
			//uncheck
			else{
				if(isReplaced){
					if(isContain){
						synonymous = '|'+synonymous;
						var replaceIndex = selection.indexOf(synonymous);
						$('#input').deleteText(selectStart + replaceIndex, selectStart + replaceIndex + synonymous.length );					$('#input').setSelection(selectStart,selectEnd - synonymous.length);
						var tmpSelectionArea = $('#input').getSelection();
						var tmpSelection = tmpSelectionArea.text;
						if(tmpSelection.indexOf('|') < 0){
							tmpSelection = tmpSelection.replace("{","");
							tmpSelection = tmpSelection.replace("}","");
							$('#input').replaceSelectedText(tmpSelection);
							$('#input').setSelection(selectStart,selectStart + tmpSelection.length );
							
						}
						
					}
				}	
			}
		});
	});
	jQuery.ajax(request);
}
